<template>
  <webview ref="webviewRef" :src="webUrl" style="width:100%;height:100%" allowpopups></webview>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ipcApiRoute } from "@/api/index.js"
import { ipc } from '@/utils/ipcRenderer'

const webviewRef = ref()
const webUrl = ref("http://192.168.30.44:3001/#/home")

// 生成 JS 注入脚本
const generateScript = (storageType) => `
  ${storageType}.setItem('admin-element-vue-token', 'admin');
  true;
`

// 统一错误处理
const handleError = (type, err) => {
  console.error(`设置 ${type} 失败：`, err)
}

const injectTokenToWebView = (useIpc = false) => {
  const key = 'admin-element-vue-token'
  const value = 'admin'

  if (useIpc) {
    // 合并 IPC 请求，减少通信次数
    ipc.invoke(ipcApiRoute.storage.setBothStorage, {
      url: webUrl.value,
      key,
      value
    })
      .then(res => {
        console.log("通过 IPC 设置 localStorage 和 sessionStorage 结果:", res)
      })
      .catch(err => {
        handleError('localStorage/sessionStorage', err)
      })

  } else {
    const execScript = (script, type) => {
      webviewRef.value.executeJavaScript(script)
        .then(result => {
          console.log(`通过 executeJavaScript 注入 ${type} 结果:`, result)
        })
        .catch(err => {
          handleError(type, err)
        })
    }

    execScript(generateScript('localStorage'), 'localStorage')
    execScript(generateScript('sessionStorage'), 'sessionStorage')
  }
}

onMounted(() => {
  const webview = webviewRef.value

  const handleDomReady = () => {
    console.log('页面 DOM 加载完成')
    injectTokenToWebView()
  }

  const handleFailLoad = (event) => {
    console.error('webview 页面加载失败:', event)
  }

  const handleFinishLoad = () => {
    console.log('页面加载完成')
    // 可选：作为 dom-ready 的补充
  }

  webview.addEventListener('dom-ready', handleDomReady)
  webview.addEventListener('did-fail-load', handleFailLoad)
  webview.addEventListener('did-finish-load', handleFinishLoad)

  // 保存监听器引用以便卸载时移除
  webview.handleDomReady = handleDomReady
  webview.handleFailLoad = handleFailLoad
  webview.handleFinishLoad = handleFinishLoad
})

onBeforeUnmount(() => {
  const webview = webviewRef.value
  if (webview.handleDomReady) {
    webview.removeEventListener('dom-ready', webview.handleDomReady)
  }
  if (webview.handleFailLoad) {
    webview.removeEventListener('did-fail-load', webview.handleFailLoad)
  }
  if (webview.handleFinishLoad) {
    webview.removeEventListener('did-finish-load', webview.handleFinishLoad)
  }
})
</script>